layui.define(['layer', 'table'], function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;
    var table = layui.table;

    var treetable = {
        // 渲染树形表格
        render: function (param) {
            // 检查参数
            if (!param.treeColIndex && param.treeColIndex != 0) {
                layer.msg('参数treeColIndex不能为空', {icon: 5});
                return;
            }

            // 默认参数
            param.elem = param.elem || '';
            param.data = param.data || [];
            param.treeSpid = param.treeSpid || 0;
            param.treeIdName = param.treeIdName || 'id';
            param.treePidName = param.treePidName || 'parent_id';
            param.treeDefaultClose = param.treeDefaultClose || false;
            param.treeLinkage = param.treeLinkage || true;

            // 处理表格渲染完成后的回调
            var done = param.done;
            param.done = function(res, curr, count) {
                // 将数据缓存到组件中
                param.data = res.data;
                
                // 渲染图标和缩进
                $('.layui-table-body tbody tr').each(function() {
                    var tr = $(this);
                    var data = table.cache[param.id][tr.data('index')];
                    if (!data) return;
                    
                    var td = tr.find('td[data-field="' + param.treeColIndex + '"]');
                    var cell = td.find('.layui-table-cell');
                    
                    // 计算缩进
                    var level = getLevel(data);
                    var indent = level * 15;
                    
                    // 添加树形图标
                    var icon = '';
                    if (hasChildren(data)) {
                        icon = '<i class="layui-icon layui-icon-triangle-d tree-table-icon open" style="cursor:pointer;margin-right:5px;"></i>';
                    }
                    
                    var content = cell.html();
                    cell.html('<div style="padding-left:' + indent + 'px">' + icon + content + '</div>');
                });

                // 绑定展开/折叠事件
                $('.layui-table-body').off('click', '.tree-table-icon').on('click', '.tree-table-icon', function(e) {
                    e.stopPropagation();
                    var icon = $(this);
                    var tr = icon.closest('tr');
                    var data = table.cache[param.id][tr.data('index')];
                    
                    if (icon.hasClass('open')) {
                        icon.removeClass('open layui-icon-triangle-d').addClass('layui-icon-triangle-r');
                        hideChildren(data);
                    } else {
                        icon.removeClass('layui-icon-triangle-r').addClass('open layui-icon-triangle-d');
                        showChildren(data);
                    }
                });

                if (done) {
                    done(res, curr, count);
                }
            };

            // 获取节点层级
            function getLevel(data) {
                var level = 0;
                var pid = data[param.treePidName];
                while (pid != param.treeSpid) {
                    level++;
                    for (var i = 0; i < param.data.length; i++) {
                        if (param.data[i][param.treeIdName] == pid) {
                            pid = param.data[i][param.treePidName];
                            break;
                        }
                    }
                    if (level > 100) break;  // 防止死循环
                }
                return level;
            }

            // 判断是否有子节点
            function hasChildren(data) {
                for (var i = 0; i < param.data.length; i++) {
                    if (param.data[i][param.treePidName] == data[param.treeIdName]) {
                        return true;
                    }
                }
                return false;
            }

            // 隐藏子节点
            function hideChildren(data) {
                $('.layui-table-body tbody tr').each(function() {
                    var tr = $(this);
                    var item = table.cache[param.id][tr.data('index')];
                    if (!item) return;
                    
                    if (isChild(item, data)) {
                        tr.hide();
                        // 如果这个节点是展开的，需要递归折叠它的子节点
                        var icon = tr.find('.tree-table-icon.open');
                        if (icon.length > 0) {
                            icon.removeClass('open layui-icon-triangle-d').addClass('layui-icon-triangle-r');
                        }
                    }
                });
            }

            // 显示子节点
            function showChildren(data) {
                $('.layui-table-body tbody tr').each(function() {
                    var tr = $(this);
                    var item = table.cache[param.id][tr.data('index')];
                    if (!item) return;
                    
                    if (item[param.treePidName] == data[param.treeIdName]) {
                        tr.show();
                    }
                });
            }

            // 判断是否为子节点
            function isChild(child, parent) {
                var pid = child[param.treePidName];
                while (pid != param.treeSpid) {
                    if (pid == parent[param.treeIdName]) {
                        return true;
                    }
                    for (var i = 0; i < param.data.length; i++) {
                        if (param.data[i][param.treeIdName] == pid) {
                            pid = param.data[i][param.treePidName];
                            break;
                        }
                    }
                    if (pid == param.treeSpid) break;
                }
                return false;
            }

            // 渲染表格
            table.render(param);
        },
        // 获取缩进的数量
        getEmptyNum: function (pid, data) {
            var num = 0;
            if (!pid) {
                return num;
            }
            var tPid;
            for (var i = 0; i < data.length; i++) {
                if (pid == data[i].id) {
                    num += 1;
                    tPid = data[i].pid;
                    break;
                }
            }
            return num + treetable.getEmptyNum(tPid, data);
        },
        // 展开/折叠行
        toggleRows: function ($dom, linkage) {
            var type = $dom.attr('lay-ttype');
            if ('file' == type) {
                return;
            }
            var mId = $dom.attr('lay-tid');
            var isOpen = $dom.hasClass('open');
            if (isOpen) {
                $dom.removeClass('open');
            } else {
                $dom.addClass('open');
            }
            $dom.closest('tbody').find('tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var pid = $ti.attr('lay-tpid');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if (mId == pid) {
                    if (isOpen) {
                        $(this).hide();
                        if ('dir' == ttype && tOpen == isOpen) {
                            $ti.trigger('click');
                        }
                    } else {
                        $(this).show();
                        if (linkage && 'dir' == ttype && tOpen == isOpen) {
                            $ti.trigger('click');
                        }
                    }
                }
            });
        },
        // 检查参数
        checkParam: function (param) {
            if (!param.treeSpid && param.treeSpid != 0) {
                layer.msg('参数treeSpid不能为空', {icon: 5});
                return false;
            }

            if (!param.treeColIndex && param.treeColIndex != 0) {
                layer.msg('参数treeColIndex不能为空', {icon: 5});
                return false;
            }
            return true;
        },
        // 展开所有
        expandAll: function (dom) {
            $(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if ('dir' == ttype && !tOpen) {
                    $ti.trigger('click');
                }
            });
        },
        // 折叠所有
        foldAll: function (dom) {
            $(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if ('dir' == ttype && tOpen) {
                    $ti.trigger('click');
                }
            });
        },
        // 处理数据
        parseData: function(data) {
            if (!data || !Array.isArray(data)) {
                return [];
            }
            var that = this;
            var options = this.config;
            var spid = options.treeSpid;
            var treeIdName = options.treeIdName;
            var treePidName = options.treePidName;
            
            // ... 其他代码
        }
    };

    exports('treetable', treetable);
}); 